<?php

class Account_Model_Activation
{
    const ACCOUNT_NOT_FOUND = 'accountNotFound';
    const ACCOUNT_INACTIVE = 'accountInactive';
    const ACCOUNT_ACTIVATED = 'accountActivated';
	// No account associated with the activation key
	const KEY_NOT_FOUND = 'keyNotFound';
	const KEY_EXPIRED = 'keyExpired';


	protected $_errorCodes = array();


	public function getErrorCodes()
	{
		return $this->_errorCodes;
	}


	public function activate($activationKey = null)
	{
		$this->_errorCodes = array();

		if (empty($activationKey) === TRUE) {
			throw new Exception('Empty activation key');
		}


		$opts = Kernel::getInstance()->getOptions();


		$statusTbl = Account_Model_DbTable_Status::getInstance();


		$select = $statusTbl->select();
		$select
			->where('status= ?', 'pending')
			->where('param= ?', $activationKey)
		;

		$statusDbRes = $statusTbl->fetchAll($select);

		if ($statusDbRes->count() < 1) {
			$this->_errorCodes[] = self::KEY_NOT_FOUND;
			return FALSE;
		}

		$statusDbRow = $statusDbRes->getRow(0);
		$accountId = $statusDbRow->account_id;

		$updRows = $statusTbl->delete(array(
				'account_id= ?' => $accountId,
				'param= ?' => $activationKey,
			));

		if ($updRows < 1) {
			throw new Exception('Query error');
		}


		// Check for expiration
		// If the key is expired, set the error flag and delete the account (a true delete)
		// and then return false

		$expiryTime = 21600;
		if (is_array($opts['account']) && is_array($opts['account']['activation'])
			&& isset($opts['account']['activation']['expiry'])) {
			$expiryTime = intval($opts['account']['activation']['expiry']);
		}


		$accountTbl = Account_Model_DbTable_Account::getInstance();

		if ($expiryTime > 0 && intval($statusDbRow->assign_time) + $expiryTime < intval(time() - date('Z'))) {
			$this->_errorCodes[] = self::KEY_EXPIRED;

			$updRows = $accountTbl->delete(array(
					'id= ?' => $accountId,
				));

			if ($updRows < 1) {
				throw new Exception('Query error');
			}

			return FALSE;
		}


		$dbData = array(
			'active' => 1,
		);

		$updRows = $accountTbl->update($dbData, array(
			'id= ?' => $accountId,
		));

		if ($updRows < 1) {
			throw new Exception('Query error');
		}


		$account = Account_Model_Account::getInstanceById($accountId);


		if (Kernel::getInstance()->isModuleActive('activity')) {
			Activity_Model_Logger::push('user', $account->getId(), 'registered');
		}


		$activationMethod = 'admin';
		if (is_array($opts['account'])) {
			$accOpts = $opts['account'];
			if (is_array($accOpts['activation']) && isset($accOpts['activation']['method'])) {
				$activationMethod = $accOpts['activation']['method'];
			}
		}


		// Don't send activation notification when the activation method is set to 'email'
		if ($activationMethod !== 'email') {

			$site_name = Kernel::getInstance()->getSiteName();
			$site_url = site_url();
			$username = $account->getNicename();
			$identity = $account->getNicename();
			$usermail = $account->getEmailAddress();

			$site_email = $opts['site']['administrator']['email'];

			ob_start();
			require CORE_PATH .'/account/mails/Activated.php';
			$mailBody = ob_get_clean();

			//DEV: email address override
			@include '../mailaddr.php';

			$mail = new Euso_Model_Mail();
			$mail->setBodyText($mailBody)
				->setFrom($site_email, $site_name)
				->addTo($usermail, $account->getNicename())
				->setSubject($site_name .' Account Activated')
			;

			$mail->send();
		}


		return TRUE;
	}

	public function resendActivationKey($identity = null)
	{
		$this->_errorCodes = array();

		if (empty($identity)) {
			throw new Exception('Empty identity');
		}


		$opts = Kernel::getInstance()->getOptions();


		$key = 'idname';
		// Check if the input is a valid email address
		$emailAddressValidator = new Zend_Validate_EmailAddress();
		if ($emailAddressValidator->isValid($identity)) {
			$key = 'email';
		}


		$accountTbl = Account_Model_DbTable_Account::getInstance();

		$select = $accountTbl->select();
		$select->where($key .'= ?', $identity);

		$accountDbRes = $accountTbl->fetchAll($select);

		if ($accountDbRes->count() !== 1) {
			$this->_errorCodes[] = self::ACCOUNT_NOT_FOUND;
			return FALSE;
		}


		$accountDbRow = $accountDbRes->getRow(0);
		$accountId = $accountDbRow->id;


		$statusTbl = Account_Model_DbTable_Status::getInstance();

		$select = $statusTbl->select();
		$select->where('account_id= ?', $accountId);

		$statusDbRes = $statusTbl->fetchAll($select);

		$statuses = array();
		foreach ($statusDbRes as $statusDbRow) {
			if ($statusDbRow->status == 'pending') {
				$activationKey = $statusDbRow->param;
			}
		}


		if (empty($activationKey)) {
			$this->_errorCodes[] = self::ACCOUNT_ACTIVATED;
			return FALSE;
		}


		$site_name = Kernel::getInstance()->getSiteName();
		$site_url = site_url();
		$username = $accountDbRow->nicename;
		$identity = $accountDbRow->nicename;
		$usermail = $accountDbRow->email;
		//CHECK: regenerate?
		$activation_key = $activationKey;
		$activation_url = site_url() .'/account/activate';
		$activation_urlkey = $activation_url .'/code/'. $activation_key;

		$site_email = $opts['site']['administrator']['email'];

		ob_start();
		require CORE_PATH .'/account/mails/ActivationKeyResend.php';
		$mailBody = ob_get_clean();

		//DEV: email address override
		@include '../mailaddr.php';

		$mail = new Euso_Model_Mail();
		$mail->setBodyText($mailBody)
			->setFrom($site_email, $site_name)
			->addTo($usermail, $accountDbRow->nicename)
			->setSubject($site_name .' Account Activation Key')
		;

		$mail->send();


		return TRUE;
	}
}